<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.model == 'bankName'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="c_index"
                ) {{ c_item.label }}
              Select(v-else-if="item.model == 'WorkFlowStatus'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="c_index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="setThead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |费用月份：
              span.text-info.pl-5.pr-5.font-weight {{$moment(salaryMonth).format('YYYY年MM月')}}
              Divider(type="vertical")
              |客户名称：
              span.text-info.pl-5.pr-5.font-weight {{customerName}}
              Divider(type="vertical")
              |客户法定名称：
              span.text-info.pl-5.pr-5.font-weight {{legalName}}
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasPostApplyUsers && !isWorkFlow" type="info" @click="isPostApplyUsers" :disabled="!selectedEmployeeId.length > 0") 申请发放
              Button.mr-10(v-if="hasPostApplyUsers && isWorkFlow" type="info" @click="handleShowApplyModal" :disabled="!selectedEmployeeId.length > 0") 申请发放
              Button.mr-10(v-if="hasExportApplyDetail" type="info" ghost @click="exportApplyDetail") 导出
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action_hasWorkFlow")
            Button.mr-10(type="text" size="small" @click="handleShowAuditDetailModal(row)" :disabled="!row.workFlowStatus") 查看审批详情
            Button(type="text" size="small" @click="handleDownLoadAttachment(row)" :disabled="!(row.attachmen && row.attachmen.path)") 附件下载
            Button.mr-10(type="text" size="small" @click="handleDownLoadPayAttachmen(row)" :disabled="!(row.payAttachmen && row.payAttachmen.path)") 付款反馈下载
          template(slot-scope="{ row, index }" slot="action")
            Button(type="text" size="small" @click="handleDownLoadAttachment(row)" :disabled="!(row.attachmen && row.attachmen.path)") 附件下载
            Button.mr-10(type="text" size="small" @click="handleDownLoadPayAttachmen(row)" :disabled="!(row.payAttachmen && row.payAttachmen.path)") 付款反馈下载

    //- 选择员工弹窗
    ChooseEmployeeModal(ref="ChooseEmployeeModal" @uploadSuccess="query")

    //- 申请发放弹窗
    ApplyModal(ref="ApplyModal" @query="query")

    //- 流程审批单弹窗
    AuditDetailModal(ref="AuditDetailModal" @query="query")
</template>

<script>
import { Common } from '@/utils/common.js'
import { OrganizationBankApi } from '@/api/OrganizationBank.api.js'
import { FinanceSPayableApi } from '@/api/FinanceSPayable.api.js'
import { ShouldPayableChildrenThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import ChooseEmployeeModal from './modal/chooseEmployeeModal.vue'
import ApplyModal from './modal/applyModal.vue'
import AuditDetailModal from "../publicModal/auditDetailModal.vue"
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  components: {
    ChooseEmployeeModal,
    ApplyModal,
    AuditDetailModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      customerName: '', // 公司名称
      legalName: '', // 公司法定名称
      employeeId: '', // 员工ID
      salaryMonth: "",
      // thead: _cloneDeep(ShouldPayableChildrenThead),
      tableColumns: _cloneDeep(ShouldPayableChildrenThead),
      thead: ['selection', 'name', 'idCardNO', 'bankName', 'accountNo', 'accountName', 'phone', 'shouldSalaryTotal', 'socialSecurityDeduct', 'providentFundDeduct', 'otherDeduct', 'incomeDeduct', 'serviceCharge', 'serviceCharge', 'realSalaryTotal', 'status', 'remark', 'backTime', 'payUser', 'payTime', 'action'],
      thead_hasWorkFlow: ['selection', 'batchID', 'name', 'idCardNO', 'bankName', 'accountNo', 'accountName', 'phone', 'shouldSalaryTotal', 'socialSecurityDeduct', 'providentFundDeduct', 'otherDeduct', 'incomeDeduct', 'serviceCharge', 'serviceCharge', 'realSalaryTotal', 'status', 'remark', 'backTime', 'payUser', 'payTime', 'workFlowStatus', 'action_hasWorkFlow'],
      tableData: [],
      formData: {
        employeeName: null,
        iDCardNo: null,
        bankName: null,
        status: null,
        WorkFlowStatus: null,
      },
      formItem: [
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'employeeName', model: 'employeeName', style: 'ivu-col-span-8' },
        { type: 'input', label: '身份证号码：', placeholder: '请输入身份证号码', prop: 'iDCardNo', model: 'iDCardNo', style: 'ivu-col-span-8' },
        { type: 'select', label: '工资发放银行：', placeholder: '请输入工资发放银行', prop: 'bankName', model: 'bankName', options: 'bankList', style: 'ivu-col-span-8' },
        { type: 'select', label: '发放状态：', placeholder: '请输入发放状态', prop: 'status', model: 'status', options: 'status', style: 'ivu-col-span-8' },
        { type: 'select', label: '审批结果：', placeholder: '请输入审批结果', prop: 'WorkFlowStatus', model: 'WorkFlowStatus', options: 'workflowstatus', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-8' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        status: [
          // {label: '待申请', value: '1'},
          // {label: '已申请', value: '2'},
          // {label: '已付款', value: '3'}
        ],
        bankList: [],
        workflowstatus: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isDelete: false
    }
  },

  watch: {
  },
  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    setThead () {
      if (this.isWorkFlow) {
        return Common.getTableColumns(this.thead_hasWorkFlow, this.tableColumns)
      } else {
        return Common.getTableColumns(this.thead, this.tableColumns)
      }
    },

    setFormItem() {
      if (this.isWorkFlow) {
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 4), ...this.formItem.slice(5, this.thead.length + 1)]
      }
    },

    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasGetList () {
      return this.actionArr.indexOf('GetList') > -1
    },
    // 导出
    hasExportApply () {
      return this.actionArr.indexOf('ExportApply') > -1
    },
    // 申请发放
    hasPostApplyUsers () {
      return this.actionArr.indexOf('PostApplyUsers') > -1
    },
    // 明细
    hasGetDetails () {
      return this.actionArr.indexOf('GetDetails') > -1
    },
    // 导出明细
    hasExportApplyDetail () {
      return this.actionArr.indexOf('ExportApplyDetail') > -1
    },
  },

  mounted () {
    this.customerName = this.$route.query.customerName
    this.legalName = this.$route.query.legalName
    this.salaryMonth = this.$route.query.salaryMonth
    this.getEnum()
    this.queryBankList()
    this.query()
  },

  methods: {
    // 数据字典
    getEnum () {
      let groupName = 'financesalary.status,finance.workflowstatus'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        ...this.formData,
        SalaryID: this.$route.query.salaryID,
        CompanyID: this.$route.query.companyID,
        SalaryMonth: this.$route.query.salaryMonth,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      console.log('详情params: ', params)
      let res = await FinanceSPayableApi.getDetails(params)
      console.log('详情res: ', res)
      if (res.status === 200 && res.data.success) {
        // this.tableData = res.data.data
        
        if (this.isWorkFlow) {
          this.tableData = res.data.data.map(item => {
            return {...item, _disabled: item.status == 1 ? false : true}
          })
        } else {
          this.tableData = res.data.data
        }
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
      } else {
        this.tableData = []
        this.tableComone.totalRows = 0
        this.tableComone.total = 0
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange(value) {
      this.selectedEmployeeArr = value.map(item => {
        return { id: item.salaryGUID, name: item.name, employeeGUID: item.employeeGUID };
      });
      this.selectedEmployeeId = value.map(item => {
        return item.salaryGUID;
      });
      console.log("列表勾选数组1", this.selectedEmployeeArr);
      console.log("列表勾选数组2", this.selectedEmployeeId);
    },

    // 获取银行下拉
    async queryBankList () {
      var params = {
        HasPaging: true,
        PageIndex: 1,
        PageSize: 100
      }
      let res = await OrganizationBankApi.getList(params)
      console.log('获取银行下拉res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.bankList = res.data.data.map(item => {return {label: item.bankName, value: item.bankName}})
      } else {
        this.arrListDown.bankList = []
      }
      this.loading = false
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
    },

    // 导出详情
    async exportApplyDetail () {
      var employeeIDs = this.selectedEmployeeArr.map(item => {
        return item.employeeGUID
      })
      var params = {
        ...this.formData,
        SalaryID: this.$route.query.salaryID,
        CompanyID: this.$route.query.companyID,
        SalaryMonth: this.$moment(this.$route.query.salaryMonth).format('YYYY-MM'),
        // HasPaging: true,
        // PageIndex: this.tableComone.pageIndex,
        // PageSize: this.tableComone.pageSize
        EmployeeIDs: employeeIDs
      }
      console.log('params: ', params)
      let res = await FinanceSPayableApi.exportApplyDetail(params)
      console.log('导出详情res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 选择员工-显示弹窗
    handleShowChooseEmployeeModal () {
      this.$refs.ChooseEmployeeModal.modalKey = 'fromDetail'
      this.$refs.ChooseEmployeeModal.show()
      this.$refs.ChooseEmployeeModal.getApplyUsers()
    },

    // 是否确认申请
    isPostApplyUsers (id,type) {
      var names = this.selectedEmployeeArr.map(item => {return item.name})
      this.$Modal.confirm({
        title: '是否确认申请发放给 ' + names,
        onOk: () => {
          this.postApplyUsers()
        },
        onCancel: () => {

        }
      })
    },    

    // 是否确认申请(含选择类型表单)-显示弹窗
    handleShowApplyModal () {
      var names = this.selectedEmployeeArr.map(item => {return item.name})
      var dataArr = this.selectedEmployeeArr.map(item => {
        return {EmployeeGUID: item.employeeGUID, Name: item.name}
      })
      this.$refs.ApplyModal.modalKey = 'fromDetail'
      this.$refs.ApplyModal.names = names.join(', ')
      this.$refs.ApplyModal.dataArr = dataArr
      this.$refs.ApplyModal.show()
      // this.$refs.ApplyModal.getApplyUsers()
    },

    // 申请发放
    async postApplyUsers () {
      var dataArr = this.selectedEmployeeArr.map(item => {
        return {EmployeeGUID: item.employeeGUID, Name: item.name}
      })
      var params = {
        IsList: false,
        SalaryID: this.$route.query.salaryID,
        CompanyID: this.$route.query.companyID,
        SalaryMonth: this.$route.query.salaryMonth,
        Datas: dataArr,
      }
      console.log('确定提交 params: ', params)
      let res = await FinanceSPayableApi.postApplyUsers(params)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    
    // 流程审批单-显示弹窗
    handleShowAuditDetailModal(row) {
      console.log('流程审批单-显示弹窗 row: ', row)
      this.$refs.AuditDetailModal.modalType = '薪资审批详情'
      this.$refs.AuditDetailModal.show(row)
    },

    // 附件下载
    handleDownLoadAttachment (row) {
      if (row.attachmen && row.attachmen.path) {
        let str = row.attachmen.path
        console.log('附件下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },

    // 付款反馈下载
    handleDownLoadPayAttachmen (row) {
      if (row.payAttachmen && row.payAttachmen.path) {
        let str = row.payAttachmen.path
        console.log('付款反馈下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
